package com.example.test;

import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;

import java.lang.reflect.Method;

/**
 * Create with Intellij idea
 * User:鲁智明
 * Date:2018/10/14
 * Time:17:57
 */
public class test008 {
    public static void main(String[] args) {
        try {
            ClassPool pool = ClassPool.getDefault();
            // 读取com.itmayiedu.User
            CtClass userClass = pool.get("com.example.entity.User");
            CtMethod method = new CtMethod(CtClass.voidType, "sum", new CtClass[] { CtClass.intType, CtClass.intType },
                    userClass);
            method.setBody("{System.out.println(\"sum:\" + ($1 + $2));}");
            // 添加方法
            userClass.addMethod(method);
            userClass.writeFile("E:/work");
            // 动态执行方法
            Class clazz = userClass.toClass();
            Object newInstance = clazz.newInstance();

            Method sumMethod = clazz.getDeclaredMethod("sum", int.class, int.class);
            System.out.println("开启事物");
            sumMethod.invoke(newInstance, 2, 5);
            // 使用 javassist 实现动态代理。
            System.out.println("提交事物");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
